package br.ufrj.dcc.xml.dynamicintervals;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.swing.text.JTextComponent;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import uxquerydemo.utils.StatisticsCollector;
import br.ufrj.dcc.xml.database.ItemManager;
import br.ufrj.dcc.xml.dynamicintervals.decoder.StringDecoder;
import br.ufrj.dcc.xml.dynamicintervals.encoding.DatabaseEncoder;

public class XMLManager {
	/**
	 * Recebe o path de um arquivo XML e armazena no BD com o devido encoding
	 * 
	 * @param outPane
	 * @param xmlFile
	 * @throws SAXException,SAXParseException
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 */
	public static int storeXml(String path, JTextComponent outPane)
			throws SAXException, SAXParseException, ParserConfigurationException, IOException {

		String xmlFile = path;

		if (xmlFile.lastIndexOf(File.separator) > 0) {
			xmlFile = xmlFile.substring(xmlFile.lastIndexOf(File.separator) + 1);
		}

		DatabaseEncoder handler = new DatabaseEncoder(
				xmlFile.replace('.', '_'));

		// Usa o parsing default (sem valida��o)
		SAXParserFactory factory = SAXParserFactory.newInstance();

		SAXParser saxParser = factory.newSAXParser();

		long before = System.nanoTime();

		saxParser.parse(new File(path), handler);

		long after = System.nanoTime();

		int idDoc = handler.getId();


		StatisticsCollector.getInstance().add("Armazenamento do documento",
				after - before);
		StatisticsCollector.getInstance().add("DOC ID", idDoc);

		try {
			StatisticsCollector.getInstance().save();
		} catch (IOException e2) {
			throw new IOException("BenchMark " + e2.getLocalizedMessage());
		}
		StatisticsCollector.resetInstance("statistics-store " + idDoc);
		
		outPane.setText(handler.getOutputText());

		return idDoc;
	}

	/**
	 * Recupera um doc Xml do banco..
	 * 
	 * @param idXmlFile,
	 * @throws IOException 
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public static String restoreXml(int idXmlFile,
			JTextComponent outSqlPane) throws IOException, SQLException {

		long before = System.nanoTime();

		ItemManager manager = new ItemManager();
		ResultSet rs = null;

		manager.testDriver();
		rs = manager.selectFullDocument(idXmlFile);

		StringDecoder dText = new StringDecoder();

		dText.decodeRS(rs);

		long after = System.nanoTime();

		outSqlPane.setText(manager.getOutputText());
		
		
		StatisticsCollector.getInstance().add("Recuperação do documento",
				after - before);
		StatisticsCollector.getInstance().add("DOC ID", idXmlFile);

		try {
			StatisticsCollector.getInstance().save();
		} catch (IOException e2) {
			System.out
					.println("Erro ao salvar arquivo de benchmark (armazenamento do documento)");
			e2.printStackTrace();
		}
		StatisticsCollector.resetInstance("statistics-restore " + idXmlFile);
		return dText.getResult();
	}

	public static void deleteXml(int id, JTextComponent outSqlPane) {

		ItemManager manager = new ItemManager();

		long before,after;
		try {
			
			before = System.nanoTime();
			
			manager.deleteDoc(id);
			after = System.nanoTime();
			
			outSqlPane.setText(manager.getOutputText());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}

		
		StatisticsCollector.getInstance().add("Remoção do documento",
				after - before);
		StatisticsCollector.getInstance().add("DOC ID", id);

		try {
			StatisticsCollector.getInstance().save();
		} catch (IOException e2) {
			System.out
					.println("Erro ao salvar arquivo de benchmark (remoção do documento)");
			e2.printStackTrace();
		}
		StatisticsCollector.resetInstance("statistics-delete " + id);
		
		
	}

	public static List listXml(JTextComponent outPane) {
		List docs = null;
		ItemManager items = new ItemManager();
		try {
			docs = items.selectDocuments();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return docs;
	}
}
